#!/bin/bash
# 停止轴承监控系统

echo "🛑 停止轴承监控系统..."

# 查找并终止相关进程
processes=$(ps aux | grep -E "(web_bearing_monitor|imu_node|rec\.py)" | grep -v grep | awk '{print $2}')

if [ -n "$processes" ]; then
    echo "发现运行中的进程:"
    ps aux | grep -E "(web_bearing_monitor|imu_node|rec\.py)" | grep -v grep
    echo ""
    
    echo "正在终止进程..."
    for pid in $processes; do
        echo "终止进程 $pid"
        kill -TERM $pid 2>/dev/null
    done
    
    # 等待进程优雅退出
    sleep 3
    
    # 强制终止仍在运行的进程
    remaining=$(ps aux | grep -E "(web_bearing_monitor|imu_node|rec\.py)" | grep -v grep | awk '{print $2}')
    if [ -n "$remaining" ]; then
        echo "强制终止残留进程..."
        for pid in $remaining; do
            kill -KILL $pid 2>/dev/null
        done
    fi
    
    echo "✅ 所有相关进程已停止"
else
    echo "✅ 没有发现运行中的监控进程"
fi

# 检查端口占用
if netstat -tuln | grep :5006 >/dev/null 2>&1; then
    echo "⚠️  端口5006仍被占用，查找占用进程..."
    lsof -ti:5006 | xargs kill -9 2>/dev/null || true
fi

echo "系统停止完成"